package com.my.goodsmanage.exception;

import com.my.goodsmanage.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @author 徐佳辉
 * @date 2020/8/11 16:08
 */
@RestControllerAdvice
@Slf4j
public class AllException {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R variableException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("和"));
        log.error(message);
        return R.error(message);
    }

    @ExceptionHandler(BindException.class)
    public R NumberFormatException(BindException e) {
        log.error(e.getMessage());
        return R.error("不能为空");
    }


    @ExceptionHandler(PhoneException.class)
    public R PhoneException(PhoneException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R unKnowException(Exception e) {
        log.error(e.getMessage());
        return R.error("未知错误，请联系管理员");
    }
}
